package com.edu.atams.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.atams.common.dto.ParentInfoDto;
import com.edu.atams.common.dto.SelectClassDto;
import com.edu.atams.common.lang.Result;
import com.edu.atams.entity.Class;
import com.edu.atams.entity.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@RestController
@RequestMapping("/student")
public class StudentController extends BaseController {

    @GetMapping("/listByClassId/{classId}")
    public Result listByClassId(@PathVariable int classId){
        List<StudentClass> studentClasses = studentClassService.list(new QueryWrapper<StudentClass>().eq("class_id", classId));
        List<Student> students = studentService.list(new QueryWrapper<Student>()
                .inSql("id", "select student_id FROM student_class where class_id = " + classId)
                .select("id","schoolNo","name"));
        return Result.succ(students);
    }


    @GetMapping("/list")
    public Result list(String schoolno, String name){
        Page<Student> page = studentService.page(getPage(), new QueryWrapper<Student>()
                .like(StrUtil.isNotBlank(schoolno), "schoolNo", schoolno)
                .like(StrUtil.isNotBlank(name), "name", name)
        );
        page.getRecords().forEach(student -> {
            StudentClass student_id = studentClassService.getOne(new QueryWrapper<StudentClass>().eq("student_id", student.getId()));
            Class classId = classService.getOne(new QueryWrapper<Class>().eq("id", student_id.getClassId()));
            Grade grade = gradeService.getOne(new QueryWrapper<Grade>().eq("id", classId.getGradeId()));
            student.setClassName(grade.getYear()+" "+grade.getName()+" "+classId.getName());
            student.setClassId(classId.getId());
        });
        return Result.succ(page);
    }

    @PostMapping("/save")
    @Transactional
    public Result save(@RequestBody Student student){
        List<Student> id_card = studentService.list(new QueryWrapper<Student>().eq("id_card", student.getIdCard()));
        if (id_card.size() > 0){
            return Result.fail("身份证重复了");
        }else {
            //生成例如2021050101的学号
            String studentno = studentService.getStudentNo(student);
            student.setSchoolno(studentno);
            studentService.save(student);
            //生成账号存入数据库
            Integer userId = sysUserService.setUserByStudent(student);
            student.setUserId(userId);
            studentService.updateById(student);
            //把班级存入数据库
            StudentClass studentClass = new StudentClass();
            studentClass.setStudentId(student.getId());
            studentClass.setClassId(student.getClassId());
            studentClassService.save(studentClass);
            return Result.succ("");
        }
    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody Student student){
        List<Student> id_card = studentService.list(new QueryWrapper<Student>().eq("id_card", student.getIdCard()).notIn("id",student.getId()));
        if (id_card.size() > 0){
            return Result.fail("身份证重复了");
        }else {

            studentService.updateById(student);

            StudentClass studentClass = new StudentClass();
            studentClass.setStudentId(student.getId());
            studentClass.setClassId(student.getClassId());
            studentClassService.update(studentClass,new QueryWrapper<StudentClass>().eq("student_id",student.getId()));
            return Result.succ("");
        }
    }

    @PostMapping("/remove")
    @Transactional
    public Result remove(@RequestBody Integer[] ids){
        List<Student> students = studentService.listByIds(Arrays.asList(ids));
        //删除学生
        studentService.removeByIds(Arrays.asList(ids));
        //删除账号
        List<Integer> userIdList = students.stream().map(student -> student.getUserId()).collect(Collectors.toList());
        sysUserService.removeByIds(userIdList);
        //删除学生-班级
        for (Integer id : ids) {
            studentClassService.remove(new QueryWrapper<StudentClass>().eq("student_id",id));
        }

        return Result.succ("");
    }

    @PostMapping("/import/{classId}/{startNum}")
    @Transactional
    public Result excelImport(@PathVariable("classId") Integer classId,@PathVariable("startNum") Integer startNum,@RequestParam("excel") MultipartFile excel) throws IOException {
        return studentService.excelImport(classId,startNum,excel);
    }

    //查看家长信息
    @GetMapping("/getParentInfo/{id}")
    public Result getParentInfo(@PathVariable("id") Integer id){
        List<StudentParent> studentParentList = studentParentService.list(new QueryWrapper<StudentParent>().eq("student_id", id));

        if (studentParentList.size() > 0){
            List<Integer> parentIdList = studentParentList.stream().map(sp -> sp.getParentId()).collect(Collectors.toList());
            List<Parent> parentList = parentService.listByIds(parentIdList);
            List<ParentInfoDto> parentInfoDtoList = new ArrayList<>();

            for (int i = 0; i < studentParentList.size(); i++) {
                ParentInfoDto parentInfoDto = new ParentInfoDto();
                parentInfoDto.setRelation(studentParentList.get(i).getFamilyRelation());
                parentInfoDto.setName(parentList.get(i).getName());
                parentInfoDto.setSex(parentList.get(i).getSex());
                parentInfoDto.setTel(parentList.get(i).getTel());
                parentInfoDtoList.add(parentInfoDto);
            }

            return Result.succ(parentInfoDtoList);
        }else {
            return Result.fail("没有查询到该学生的家长信息呢");
        }
    }
    @GetMapping("/getstudentclass/{id}")
    public Result getStudentClass(@PathVariable("id") Integer studentid){
        System.out.println(studentid);
        SelectClassDto selectClassDto=new SelectClassDto();
        Integer classid=studentClassService.getOne(new QueryWrapper<StudentClass>().in("student_id",studentid)).getClassId();
        selectClassDto.setId(classid);
        Class classes=classService.getOne(new QueryWrapper<Class>().in("id",classid));
        Grade grade=gradeService.getOne(new QueryWrapper<Grade>().in("id",classes.getGradeId()));
        String classname=grade.getYear()+grade.getName()+classes.getName();
        selectClassDto.setName(classname);
        List<ClassSubject> classSubjects=classSubjectService.list(new QueryWrapper<ClassSubject>().in("class_id",classid));
        selectClassDto.setTeacherNum(classSubjects.size());
        List<StudentClass> studentClasses=studentClassService.list(new QueryWrapper<StudentClass>().in("class_id",classid));
        selectClassDto.setStudentNum(studentClasses.size());
        List<Integer> studentids=studentClasses.stream().map(StudentClass::getStudentId).collect(Collectors.toList());
        List<StudentParent> studentParents=studentParentService.list(new QueryWrapper<StudentParent>().in("student_id",studentids));
        selectClassDto.setParentNum(studentParents.size());
        return Result.succ(selectClassDto);
    }


}
